#!/bin/bash

Moodle_Selection()
{
    #set Moodle admin email
    echo "==========================="
    MoodleAdminEmail="hongm@sina.com"
    echo -e " \e[0;33mPlease setup E-mail of Moodle Admin.(Default email: admin@163.com)\e[0m"
    read -p "Please enter: " MoodleAdminEmail
    if [ "${MoodleAdminEmail}" = "" ]; then
         MoodleAdminEmail="admin@163.com"
    fi
    echo -e " \e[0;32mMoodle admin E-mail: \e[0;31m${MoodleAdminEmail}\e[0m"

    #which Moodle Version do you want to install?
    echo "==========================="
Moodle_Ver1=$[${MOODLE_STABLE_VERSION}+1]
Moodle_Ver2=${MOODLE_STABLE_VERSION}
Moodle_Ver3=$[${MOODLE_STABLE_VERSION}-1]
Moodle_Ver4=$[${MOODLE_STABLE_VERSION}-2]
Moodle_Ver5=$[${MOODLE_STABLE_VERSION}-3]
Moodle_Ver6=$[${MOODLE_STABLE_VERSION}-4]
Moodle_Ver7=$[${MOODLE_STABLE_VERSION}-5]
Moodle_Ver8=$[${MOODLE_STABLE_VERSION}-6]
Moodle_Ver9=$[${MOODLE_STABLE_VERSION}-7]
Moodle_Ver0=19
    MoodleSelect="8"
    echo -e " \e[0;33mYou have 5 options for your Moodle install.\e[0m"
    echo -e "   \e[0;31m0\e[0m: Install Moodle 1.9 (Legacy releases)"
    echo -e "   \e[0;31m1\e[0m: Install Moodle ${Moodle_Ver9:0:1}.${Moodle_Ver9:1:1} (Legacy releases)"
    echo -e "   \e[0;31m2\e[0m: Install Moodle ${Moodle_Ver8:0:1}.${Moodle_Ver8:1:1} (Legacy releases)"
    echo -e "   \e[0;31m3\e[0m: Install Moodle ${Moodle_Ver7:0:1}.${Moodle_Ver7:1:1} (Legacy releases)"
    echo -e "   \e[0;31m4\e[0m: Install Moodle ${Moodle_Ver6:0:1}.${Moodle_Ver6:1:1} (Legacy releases)"
    echo -e "   \e[0;31m5\e[0m: Install Moodle ${Moodle_Ver5:0:1}.${Moodle_Ver5:1:1} (Legacy releases)"
    echo -e "   \e[0;31m6\e[0m: Install Moodle ${Moodle_Ver4:0:1}.${Moodle_Ver4:1:1} (Security-only-supported releases)"
    echo -e "   \e[0;31m7\e[0m: Install Moodle ${Moodle_Ver3:0:1}.${Moodle_Ver3:1:1} (Other supported releases)"
    echo -e "   \e[0;31m8\e[0m: Install Moodle ${Moodle_Ver2:0:1}.${Moodle_Ver2:1:1} (Latest release)\e[44;37m(Default)\e[0m"
    echo -e "   \e[0;31m9\e[0m: Install Moodle ${Moodle_Ver1:0:1}.${Moodle_Ver1:1:1} (Development release)"
    read -p "Enter your choice (0, 1, 2, 3, 4, 5, 6, 7, 8 or 9): " MoodleSelect
    if [ "${MoodleSelect}" = "" ]; then
        MoodleSelect=8
    fi
    if [ "${MoodleSelect}" = "0" ]; then
        CurMoodleVer=19
     else
        CurMoodleVer=$[${MOODLE_STABLE_VERSION}+${MoodleSelect}-8]
    fi
    MoodleVer="MOODLE_${CurMoodleVer}_STABLE"
    if [ "${MoodleSelect}" = "9" ]; then
        MoodleVer="master"
    fi
    Moodle_Version=${CurMoodleVer:0:1}.${CurMoodleVer:1:1}
    echo -e " \e[0;32mNo input,You will install \e[0;31mMoodle ${Moodle_Version}\e[0m"


    echo "======================================"
    domain=""
    read -p "Please enter domain(example: www.moodle.org): " domain
    if [ "${domain}" = "" ]; then
        echo "No enter,domain name can't be empty."
        exit 1
    fi
    if [ ! -f "/usr/local/nginx/conf/vhost/${domain}.conf" ]; then
        echo -e " \e[0;32mYour domain: \e[0;31m${domain}\e[0m"
     else
        echo -e " \e[0;32m${domain} is exist!\e[0m"
    fi
}

Start_Moodle()
{
    echo ""
    echo "Press any key to install...or Press Ctrl+c to cancel"
    OLDCONFIG=`stty -g`
    stty -icanon -echo min 1 time 0
    dd count=1 2>/dev/null
    stty ${OLDCONFIG}
}

Install_Moodle()
{
    echo -e " \e[0;32m[+] Create ${domain} configuration ...\e[0m"
    if [[ "${Stack}" = "lamp" ]]; then
        vhostconf="/usr/local/apache/conf/vhost/${domain}.conf"
        echo "<VirtualHost *:80>" >${vhostconf}
        echo "ServerAdmin ${ServerAdmin}" >>${vhostconf}
        echo "php_admin_value open_basedir \"${Default_Moodle_Dir}/moodle:${Default_Moodle_Dir}/moodledata:/tmp/:/var/tmp/:/proc/\"" >>${vhostconf}
        echo "DocumentRoot \"${Default_Moodle_Dir}/moodle\"" >>${vhostconf}
        echo "ServerName ${domain}" >>${vhostconf}
        echo "ErrorLog \"/home/wwwlogs/${domain}-error_log\"" >>${vhostconf}
        echo "CustomLog \"/home/wwwlogs/${domain}-access_log\" common" >>${vhostconf}
        echo "<Directory \"${Default_Moodle_Dir}/moodle\">" >>${vhostconf}
        echo "    SetOutputFilter DEFLATE" >>${vhostconf}
        echo "    Options FollowSymLinks" >>${vhostconf}
        echo "    AllowOverride All" >>${vhostconf}
        echo "    Order allow,deny" >>${vhostconf}
        echo "    Allow from all" >>${vhostconf}
        echo "    DirectoryIndex index.html index.php" >>${vhostconf}
        echo "</Directory>" >>${vhostconf}
        echo "</VirtualHost>" >>${vhostconf}
        /etc/init.d/httpd restart
     else
        vhostconf="/usr/local/nginx/conf/vhost/${domain}.conf"
        echo 'server' >${vhostconf}
        echo '    {' >>${vhostconf}
        echo '        listen 80;' >>${vhostconf}
        echo '        #listen [::]:80;' >>${vhostconf}
        echo "        server_name ${domain};" >>${vhostconf}
        echo '        index index.html index.htm index.php default.html default.htm default.php;' >>${vhostconf}
        echo "        root  ${Default_Moodle_Dir}/moodle;" >>${vhostconf}
        echo '#memc        location /memc {' >>${vhostconf}
        echo '#memc            internal;' >>${vhostconf}
        echo '#memc            memc_connect_timeout 100ms;' >>${vhostconf}
        echo '#memc            memc_send_timeout 100ms;' >>${vhostconf}
        echo '#memc            memc_read_timeout 100ms;' >>${vhostconf}
        echo '#memc            set $memc_key $query_string;' >>${vhostconf}
        echo '#memc            set $memc_exptime 300;' >>${vhostconf}
        echo '#memc            memc_pass memcache;' >>${vhostconf}
        echo '#memc        }' >>${vhostconf}
        echo '        include moodle.conf;' >>${vhostconf}
        echo '        location ~ [^/]\.php(/|$)' >>${vhostconf}
        echo '        {' >>${vhostconf}
        echo '#memc            set $key $uri$args;' >>${vhostconf}
        echo '#memc            srcache_fetch GET /memc $key;' >>${vhostconf}
        echo '#memc            srcache_store PUT /memc $key;' >>${vhostconf}
        echo '            fastcgi_pass  unix:/dev/shm/php-cgi.sock;' >>${vhostconf}
        echo '            fastcgi_index index.php;' >>${vhostconf}
        echo '            include fastcgi.conf;' >>${vhostconf}
        echo '            include pathinfo.conf;' >>${vhostconf}
        echo '        }' >>${vhostconf}
        echo '        access_log off;' >>${vhostconf}
        echo '    }' >>${vhostconf}
        if ! grep -Eqi "^#memc" /usr/local/nginx/conf/nginx.conf &&  /usr/local/nginx/sbin/nginx -V 2>&1 | grep -Eqi 'memc-nginx' ; then
            sed -i 's:^#memc::g' ${vhostconf}
        fi
        /etc/init.d/nginx restart
    fi

    echo -e " \e[0;32m[+] Download Moodle Git Clone ...\e[0m"
    cd ${cur_dir}/src
    if [ -s "${MoodleFileName}.00" ]; then
        echo "${MoodleFileName} [found]"
     else
        echo "Error: ${MoodleFileName} not found!!!download now..."
        Download_Files ${Download_Mirror}/moodle/${MoodleFileName}.00 ${MoodleFileName}.00
        Download_Files ${Download_Mirror}/moodle/${MoodleFileName}.01 ${MoodleFileName}.01
        Download_Files ${Download_Mirror}/moodle/${MoodleFileName}.02 ${MoodleFileName}.02
        Download_Files ${Download_Mirror}/moodle/${MoodleFileName}.03 ${MoodleFileName}.03
        [[ ! -f ${MoodleFileName}.00 ]] && wget -c ${Download_MirrorSlave}/moodle/${MoodleFileName}.00
        [[ ! -f ${MoodleFileName}.01 ]] && wget -c ${Download_MirrorSlave}/moodle/${MoodleFileName}.01
        [[ ! -f ${MoodleFileName}.02 ]] && wget -c ${Download_MirrorSlave}/moodle/${MoodleFileName}.02
        [[ ! -f ${MoodleFileName}.03 ]] && wget -c ${Download_MirrorSlave}/moodle/${MoodleFileName}.03
    fi

    echo -e " \e[0;32m[+] Install Moodle Soucre...\e[0m"
    mkdir -p ${Default_Moodle_Dir}
    if [ -s "${MoodleFileName}.00" ]; then
        cat ${MoodleFileName}.* |tar xz -C ${Default_Moodle_Dir}/
        cd ${Default_Moodle_Dir}/moodle
        git reset --hard
        git pull
        if [ "${MoodleSelect}" = "9" ]; then
            git reset --hard origin/${MoodleVer}
         else
            git branch --track ${MoodleVer} origin/${MoodleVer}
            git checkout ${MoodleVer}
        fi
        git pull
     else
        echo "Moodle ${Moodle_Version} Not Found!! download now..."
        if [ "${MoodleSelect}" = "9" ]; then
            wget -c https://download.moodle.org/download.php/direct/moodle/moodle-latest.tgz
            tar zxf moodle-latest.tgz -C ${Default_Moodle_Dir}/
            rm -f moodle-latest.tgz
         else
            wget -c http://download.moodle.org/download.php/direct/stable${CurMoodleVer}/moodle-latest-${CurMoodleVer}.tgz
            tar zxf moodle-latest-${CurMoodleVer}.tgz -C ${Default_Moodle_Dir}/
            rm -f moodle-latest-${CurMoodleVer}.tgz
        fi
    fi

    cd ${cur_dir}/src
    MoodleConfigFile="${Default_Moodle_Dir}/moodle/config.php"
    echo '<?PHP  // Moodle configuration file' > ${MoodleConfigFile}
    echo 'unset($CFG);' >> ${MoodleConfigFile}
    echo 'global $CFG;' >> ${MoodleConfigFile}
    echo '$CFG = new stdClass();' >> ${MoodleConfigFile}
    echo '$CFG->dbtype    = "mariadb";' >> ${MoodleConfigFile}
    echo '$CFG->dblibrary = "native";' >> ${MoodleConfigFile}
    echo '$CFG->dbhost    = "localhost";' >> ${MoodleConfigFile}
    echo '$CFG->dbname    = "moodle";' >> ${MoodleConfigFile}
    echo '$CFG->dbuser    = "moodle";' >> ${MoodleConfigFile}
    echo "\$CFG->dbpass    = \"${DB_Root_Password}\";" >> ${MoodleConfigFile}
    echo '$CFG->prefix    = "mdl_";' >> ${MoodleConfigFile}
    echo '$CFG->dboptions = array(' >> ${MoodleConfigFile}
    echo '  "dbpersist" => 0,' >> ${MoodleConfigFile}
    echo '  "dbport" => "",' >> ${MoodleConfigFile}
    echo '  "dbsocket" => "",' >> ${MoodleConfigFile}
    echo ');' >> ${MoodleConfigFile}
    echo "\$CFG->wwwroot   = \"http://${domain}\";" >> ${MoodleConfigFile}
    echo '$CFG->dataroot  = "'${Default_Moodle_Dir}'/moodledata";' >> ${MoodleConfigFile}
    echo '$CFG->directorypermissions = 0777;' >> ${MoodleConfigFile}
    echo '$CFG->admin = "admin";' >> ${MoodleConfigFile}
    echo 'require_once(dirname(__FILE__) . "/lib/setup.php"); // Do not edit' >> ${MoodleConfigFile}
    mkdir -p ${Default_Moodle_Dir}/moodledata
    chown -R www:www ${Default_Moodle_Dir}/moodle
    chown -R www:www ${Default_Moodle_Dir}/moodledata
    chmod -R 755 ${Default_Moodle_Dir}/moodle
    chmod -R 755 ${Default_Moodle_Dir}/moodledata
    find ${Default_Moodle_Dir}/moodle -type f -exec chmod 0644 {} \;

    echo -e " \e[0;32m[+] Install Moodle DataBase ...\e[0m"
    echo "grant all on moodle.* to 'moodle'@'localhost' identified by '${DB_Root_Password}';" > /tmp/mariadb_sec_script
    echo "flush privileges;" >> /tmp/mariadb_sec_script
    echo "CREATE DATABASE moodle DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;" >> /tmp/mariadb_sec_script
    /usr/bin/mysql -u root -p${DB_Root_Password} -h localhost < /tmp/mariadb_sec_script
    n=0
    while [ $n -le 8 ] && [ ! -f ${MySQL_Data_Dir}/moodle/mdl_user.frm ] && [ ! -f ${DB_Data_Dir}/moodle/mdl_user.frm ]
    do
        /usr/bin/php ${Default_Moodle_Dir}/moodle/admin/cli/install_database.php --lang=zh_cn --adminpass=${DB_Root_Password} --adminemail=${MoodleAdminEmail} --fullname=ITCenter --shortname=ITCenter --agree-license
        n=$((n+1))
    done

    if [ $n -ge 8 ]; then
        echo "Network error! Please continue to install http://${domain} in the browser!"
     else
        /usr/bin/mysql -u root -p${DB_Root_Password} -h localhost -e "UPDATE moodle.mdl_config SET value='firstname,lastname' WHERE name='alternativefullnameformat';"
        /usr/bin/mysql -u root -p${DB_Root_Password} -h localhost -e "UPDATE moodle.mdl_config SET value='0' WHERE name='defaulthomepage';"
        /usr/bin/mysql -u root -p${DB_Root_Password} -h localhost -e "UPDATE moodle.mdl_config SET value='CN' WHERE name='country';"
        /usr/bin/mysql -u root -p${DB_Root_Password} -h localhost -e "UPDATE moodle.mdl_config SET value='Asia/Shanghai' WHERE name='timezone';"
        /usr/bin/mysql -u root -p${DB_Root_Password} -h localhost -e "UPDATE moodle.mdl_config SET value='' WHERE name='docroot';"
        /usr/bin/php ${Default_Moodle_Dir}/moodle/admin/cli/mysql_compressed_rows.php -f
    fi
    cd ${cur_dir}/src
    Download_Files ${Download_Mirror}/moodle/langpack/zh_cn_local.tar.gz zh_cn_local.tar.gz
    if  [ -f zh_cn_local.tar.gz ]; then
        tar zxf zh_cn_local.tar.gz -C ${Default_Moodle_Dir}/moodledata/lang
    fi
    rm -f /tmp/mariadb_sec_script
}

Print_Moodle_Info()
{
    echo "+------------------------------------------------------------------------"
    echo "|         LNMP V${LNMP_Ver} for ${DISTRO} Linux Server, Written by Hongm"
    echo "+------------------------------------------------------------------------"
    echo "|    lnmp status manage: lnmp {start|stop|reload|restart|kill|status}"
    echo "+------------------------------------------------------------------------"
    echo "|  phpMyAdmin: http://IP/phpmyadmin/"
    echo "|  phpinfo: http://IP/phpinfo.php"
    echo "|  Prober:  http://IP/p.php"
    echo "+------------------------------------------------------------------------"
    echo "|  Add VirtualHost: lnmp vhost add"
    echo "+------------------------------------------------------------------------"
    echo "|  Default directory: /home/wwwroot/default"
    echo "+------------------------------------------------------------------------"
    echo "|  MySQL/MariaDB root password: ${DB_Root_Password}"
    echo "+------------------------------------------------------------------------"
    echo "|  Your Moodle WebSite: http://${domain}"
    echo "|     Home Directory: ${Default_Moodle_Dir}/moodle"
    echo "|     Data Directory: ${Default_Moodle_Dir}/moodledata"
    echo "+------------------------------------------------------------------------"
    Echo_Green "Install ${Stack} V${LNMP_Ver} and Moodle completed! enjoy it."
}
